package com.yiwei.ydd.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.ydd.R;
import com.yiwei.ydd.adapter.RechargeTypeAdapter;
import com.yiwei.ydd.api.Api;
import com.yiwei.ydd.api.bean.PagesDetailBean;
import com.yiwei.ydd.api.model.RechargeInstantModel;
import com.yiwei.ydd.api.model.ShareInfoModel;
import com.yiwei.ydd.base.BaseActivity;
import com.yiwei.ydd.constant.UserInfoGlobal;
import com.yiwei.ydd.event.BuyVipUpSuccessEvent;
import com.yiwei.ydd.event.OilcardAddSuccess;
import com.yiwei.ydd.util.Arith;
import com.yiwei.ydd.util.Dialog;
import com.yiwei.ydd.util.Network;
import com.yiwei.ydd.util.NowStepDialog;
import com.yiwei.ydd.util.RxLifeUtil;
import com.yiwei.ydd.util.ShareUtil;
import com.yiwei.ydd.util.Spans;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.util.Util;
import com.yiwei.ydd.view.InputMoneyDialog;
import com.yiwei.ydd.view.OilChangeDialog;
import com.yiwei.ydd.view.V19RelativeLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class NowRechargeActivity extends BaseActivity {

    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.list_type)
    RecyclerView listType;
    @BindView(R.id.btn_tips)
    SuperButton btnTips;
    @BindView(R.id.layout_empty_oilcard)
    LinearLayout layoutEmptyOilcard;
    @BindView(R.id.layout_has_oilcard)
    RelativeLayout layoutHasOilcard;
    @BindView(R.id.txt_recharge_total)
    TextView txtRechargeTotal;
    @BindView(R.id.txt_actual_total)
    TextView txtActualTotal;
    @BindView(R.id.txt_oil_type)
    TextView txtOilType;
    @BindView(R.id.txt_oil_card)
    TextView txtOilCard;
    @BindView(R.id.img_icon)
    ImageView imgIcon;
    @BindView(R.id.btn_back)
    ImageView btnBack;

    @BindView(R.id.layout_title)
    V19RelativeLayout layoutTitle;
    @BindView(R.id.btn_oil_change)
    TextView btnOilChange;
    @BindView(R.id.txt_tips)
    TextView txtTips;
    @BindView(R.id.txt_bottom_one)
    TextView txtBottomOne;
    @BindView(R.id.txt_bottom_two)
    TextView txtBottomTwo;
    @BindView(R.id.btn_recharge)
    TextView btnRecharge;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.btn_notice_close)
    ImageView btnNoticeClose;
    @BindView(R.id.btn_notice)
    FrameLayout btnNotice;
    @BindView(R.id.view_step_one)
    View viewStepOne;
    @BindView(R.id.view_three)
    View viewThree;

    private Unbinder unbiner;
    private RechargeTypeAdapter adapter;
    private OilChangeDialog oilChangeDialog;
    private String paymentType;
    private String select_oilcard_id;
    private String select_money_total;
    private String select_actual_money;

    private boolean isCheckAll = false;
    private int x24;
    private double sale;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge_now);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BuyVipUpSuccessEvent event) {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(OilcardAddSuccess event) {
        getOilCardList();
    }

    private void init() {
        x24 = getResources().getDimensionPixelSize(R.dimen.x24);
        txtTitle.setText("即时充值");
        Spanned txt_tips = Spans.with(this).font("温馨提示：\n1.即时充值，当天下单后2-48小时内到账\n2.银卡会员身份可享受最低", x24, 0xff999999).
                font("9.9", x24, 0xffFF0030).
                font("折优惠\n3.金卡会员身份可享受最低", x24, 0xff999999).
                font("9.8", x24, 0xffFF0030).
                font("折优惠\n4.铂金会员身份可享受最低", x24, 0xff999999).
                font("9.7", x24, 0xffFF0030).
                font("折优惠", x24, 0xff999999).
                build();
        txtTips.setText(txt_tips);

        txtRechargeTotal.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        oilChangeDialog = new OilChangeDialog(this);
        oilChangeDialog.setDialogClickListener(new OilChangeDialog.DialogDefaultClickListener() {
            @Override
            public void confirm(String id, String ctype, String card_number) {
                select_oilcard_id = id;
                if (ctype.equals("1")) {
                    txtOilType.setText("中国石化");
                    imgIcon.setImageResource(R.mipmap.img_shihua_two_map);
                } else if (ctype.equals("2")) {
                    txtOilType.setText("中国石油");
                    imgIcon.setImageResource(R.mipmap.img_shiyou_two_map);
                }
                txtOilCard.setText(card_number);
            }

            @Override
            public void cancel() {

            }
        });
        listType.setLayoutManager(new GridLayoutManager(this, 3));
        adapter = new RechargeTypeAdapter(this);
        adapter.setOnChooseListener(new RechargeTypeAdapter.OnChooseListener() {
            @Override
            public void onClick(int poi, String money, String sale_money) {
                if (poi == (adapter.getItemCount() - 1)) {
                    select_money_total = "";
                    new InputMoneyDialog(NowRechargeActivity.this).setDialogClickListener(new InputMoneyDialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm(String money) {
                            String total_money = money;
                            String sale_true_money = Arith.mul(Arith.mul(sale, 0.01), Double.valueOf(money)) + "";
                            adapter.getmSource().get(adapter.getItemCount() - 1).money = total_money;
                            adapter.getmSource().get(adapter.getItemCount() - 1).sale_money = sale_true_money;
                            adapter.notifyDataSetChanged();
                            select_money_total = total_money;
                            select_actual_money = sale_true_money;
                            txtRechargeTotal.setText("￥" + total_money);
                            txtActualTotal.setText("￥" + sale_true_money);
                        }
                    }).show();
                    return;
                }
                select_money_total = money;
                select_actual_money = sale_money;
                txtRechargeTotal.setText("￥" + money);
                txtActualTotal.setText("￥" + sale_money);
            }
        });
        listType.setAdapter(adapter);

        getRechargeInstant();
        getOilCardList();


    }

    private void showStepDialog() {
        NowStepDialog.showStepOne(this);
    }

    //    ===========================获取即时充值列表===========================
    public void getRechargeInstant() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        Api.api_service.getRechargeInstant().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.datas.item != null && result.datas.item.size() != 0) {
//                        RechargeInstantModel.DatasBean.ItemBean bean = new RechargeInstantModel.DatasBean.ItemBean();
//                        bean.id = "10";
//                        bean.recommend = "0";
//                        bean.money = "+ 自定义";
//                        bean.sale_money = "0";
//                        result.datas.item.add(bean);
                        adapter.setSaleNum(Arith.mul(Double.valueOf(result.datas.sale), 0.1) + "");
                        for (int i = 0; i < result.datas.item.size(); i++) {
                            RechargeInstantModel.DatasBean.ItemBean item = result.datas.item.get(i);
                            if (item.recommend.equals("1") && Float.valueOf(item.inventory) > 0) {
                                item.isCheck = true;
                                select_money_total = item.money;
                                select_actual_money = item.sale_money;
                                txtRechargeTotal.setText("￥" + item.money);
                                txtActualTotal.setText("￥" + item.sale_money);
                            }
                        }
                        adapter.update(result.datas.item);
                    }
                    sale = Double.valueOf(result.datas.sale);
                    if (TextUtils.isEmpty(result.datas.note)) {
                        btnTips.setVisibility(View.GONE);
                    } else {
                        btnTips.setVisibility(View.VISIBLE);
                        btnTips.setText(result.datas.note);
                    }
                    if (UserInfoGlobal.getNowStepLead()) {
                        showStepDialog();
                        UserInfoGlobal.setNowStepLead(false);
                    }
                });
    }
    //    ===========================获取即时充值列表===========================


    //    ===========================获取油卡列表===========================
    public void getOilCardList() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        Api.api_service.getOilcardList().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (isCheckAll) {
                        oilChangeDialog.setData(result.datas);
                        oilChangeDialog.show();
                        isCheckAll = false;
                        return;
                    }
                    if (result.datas != null && result.datas.size() != 0) {
                        layoutHasOilcard.setVisibility(View.VISIBLE);
                        layoutEmptyOilcard.setVisibility(View.GONE);

                        if (result.datas.size() == 1) {
                            select_oilcard_id = result.datas.get(0).id;
                            if (result.datas.get(0).ctype.equals("1")) {
                                txtOilType.setText("中国石化");
                                imgIcon.setImageResource(R.mipmap.img_shihua_two_map);
                            } else if (result.datas.get(0).ctype.equals("2")) {
                                txtOilType.setText("中国石油");
                                imgIcon.setImageResource(R.mipmap.img_shiyou_two_map);
                            }
                            txtOilCard.setText(result.datas.get(0).card_number);
                        } else {

                            for (int i = 0; i < result.datas.size(); i++) {
                                if (result.datas.get(i).isdefault.equals("1")) {
                                    select_oilcard_id = result.datas.get(i).id;
                                    if (result.datas.get(i).ctype.equals("1")) {
                                        txtOilType.setText("中国石化");
                                        imgIcon.setImageResource(R.mipmap.img_shihua_two_map);
                                    } else if (result.datas.get(i).ctype.equals("2")) {
                                        txtOilType.setText("中国石油");
                                        imgIcon.setImageResource(R.mipmap.img_shiyou_two_map);
                                    }
                                    txtOilCard.setText(result.datas.get(i).card_number);

                                    return;
                                }
                            }

                            select_oilcard_id = result.datas.get(0).id;
                            if (result.datas.get(0).ctype.equals("1")) {
                                txtOilType.setText("中国石化");
                                imgIcon.setImageResource(R.mipmap.img_shihua_two_map);
                            } else if (result.datas.get(0).ctype.equals("2")) {
                                txtOilType.setText("中国石油");
                                imgIcon.setImageResource(R.mipmap.img_shiyou_two_map);
                            }
                            txtOilCard.setText(result.datas.get(0).card_number);

                        }

                    } else {
                        layoutHasOilcard.setVisibility(View.GONE);
                        layoutEmptyOilcard.setVisibility(View.VISIBLE);
                    }

                });
    }
    //    ===========================获取油卡列表===========================


    public void getShareInfo() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getShareInfo().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ShareInfoModel.DatasBean item = result.datas;
                    ShareUtil.share(this, item.desc, item.image, item.title, item.url);
                });
    }

    public void getPagesDetail() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        PagesDetailBean item = new PagesDetailBean();
        item.keyword = "recharge";
        loadingDialog.show();
        Api.api_service.getPagesDetail(item).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Intent intent1 = new Intent(this, WebViewActivity.class);
                    intent1.putExtra("content", result.datas.content);
                    intent1.putExtra("title", result.datas.title);
                    startActivity(intent1);
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_notice_close, R.id.btn_notice, R.id.layout_empty_oilcard, R.id.txt_right, R.id.btn_back, R.id.btn_oil_change, R.id.btn_tips, R.id.btn_recharge})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_oil_change:
                isCheckAll = true;
                getOilCardList();
                break;
            case R.id.txt_right:
//                Intent intent2 = new Intent(this, WebViewActivity.class);
//                intent2.putExtra("url", UserInfoGlobal.getQuestions());
//                intent2.putExtra("title", "常见问题");
//                startActivity(intent2);
                Util.startActivity(this, AllTipsActivity.class);
                break;
            case R.id.layout_empty_oilcard:
                Util.startActivity(this, OilCardAddActivity.class);

                break;
            case R.id.btn_notice_close:
                btnNotice.setVisibility(View.GONE);
                break;
            case R.id.btn_notice:
                getPagesDetail();
                break;

            case R.id.btn_back:


                finish();
                break;
            case R.id.btn_tips:
                if(Util.getIsLogin(this))
                Util.startActivity(this, VipLevelUpTipsActivity.class);
                break;
            case R.id.btn_recharge:

                if (TextUtils.isEmpty(select_money_total)) {
                    ToastUtil.makeText(this, "请选择要充值的金额");
                    return;
                }
                if (TextUtils.isEmpty(select_oilcard_id)) {
//                    ToastUtil.makeText(this, "请选择一张油卡");

                    Dialog.showGuestrueDialog(this, "", "您目前还没有添加加油卡，支付成功后可以在“我的订单”里进行添加，您是否继续支付？", "取消", "继续支付", new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            Intent intent = new Intent(NowRechargeActivity.this, OilcardOrderPayMoneyActivity.class);
                            intent.putExtra("money", select_money_total);
                            intent.putExtra("sale_money", select_actual_money);
                            intent.putExtra("oilcard_id", select_oilcard_id);
                            intent.putExtra("is_now_oil", true);
                            startActivity(intent);
                            overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                    return;
                }


                Intent intent = new Intent(this, OilcardOrderPayMoneyActivity.class);
                intent.putExtra("money", select_money_total);
                intent.putExtra("sale_money", select_actual_money);
                intent.putExtra("oilcard_id", select_oilcard_id);
                intent.putExtra("is_now_oil", true);
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
        }

    }


}
